package site.mmda.controller;

import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import site.mmda.entity.Room;
import site.mmda.entity.User;
import site.mmda.util.UUIDUtils;
import site.mmda.vo.ResponseResult;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 廉壮
 * @version 1.0
 * @date 2024-05-30 18:28
 */
@RestController
@RequestMapping("/goController")
public class GoController {


    private ConcurrentHashMap<String,Room> roomPool = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, User> userEmmitPool = new ConcurrentHashMap<>();


    @PostMapping("/createRoom")
    public ResponseResult createRoom(@RequestBody Object o){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        LocalDateTime now = LocalDateTime.now();
        String uuid = UUIDUtils.getId();
        Room room = new Room();
        room.setId(uuid);
        room.setCreateByUserId(userId);
        room.setCreateTime(now);
        room.setName(userName+"的房间");

        User user = new User();
        user.setUserId(userId);
        user.setUserName(userName);
        HashMap<Long, User> longUserHashMap = new HashMap<>();
        longUserHashMap.put(user.getUserId(),user);
        room.setUserMap(longUserHashMap);
        ArrayList<Long> userIdList = new ArrayList<>();
        userIdList.add(user.getUserId());
        room.setUserIdList(userIdList);
        roomPool.put(room.getId(), room);
        return ResponseResult.success(room);
    }

    @GetMapping("/getSse/room/{roomId}")
    public SseEmitter getSseOfRoom(@PathVariable("roomId") String roomId){
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        Room room = roomPool.get(roomId);
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        room.getUserMap().get(userId).setRoomEmitter(sseEmitter);
        return sseEmitter;
    }

}
